﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace NinjaToolbox
{
    public class TimeSlowerManager : MonoBehaviour
    {
        static bool applicationIsQuitting = false;

        static TimeSlowerManager mInstance;
        public static TimeSlowerManager Instance
        {
            get
            {
                if (applicationIsQuitting) return null;

                if (mInstance == null)
                {
                    mInstance = new GameObject("[TimeSlowerManager]").AddComponent<TimeSlowerManager>();
                    UnityEngine.Object.DontDestroyOnLoad(mInstance.gameObject);
                }

                return mInstance;
            }
        }

        public class TimeScaleHandler
        {
            public float ExpectTimeScale { get; set; }
        }

        float mBaseTimeScale;
        List<TimeScaleHandler> mTimeScaleHandlerList = new List<TimeScaleHandler>(10);

        public float BaseTimeScale { get { return mBaseTimeScale; } }


        public void SetBaseTimeScale(float baseTimeScale)
        {
            mBaseTimeScale = baseTimeScale;
        }

        public TimeScaleHandler RegistTimeScaleHandler()
        {
            var result = new TimeScaleHandler() { ExpectTimeScale = mBaseTimeScale };

            mTimeScaleHandlerList.Add(result);

            return result;
        }

        public void UnregistTimeScaleHandler(TimeScaleHandler handler)
        {
            mTimeScaleHandlerList.Remove(handler);
        }

        void Awake()
        {
            mBaseTimeScale = 1f;
        }

        void Update()
        {
            var finalTimeScale = mBaseTimeScale;
            for (int i = 0, iMax = mTimeScaleHandlerList.Count; i < iMax; i++)
            {
                finalTimeScale = Mathf.Min(finalTimeScale, mTimeScaleHandlerList[i].ExpectTimeScale);
            }

            Time.timeScale = finalTimeScale;
        }

        void OnDestroy()
        {
            applicationIsQuitting = true;
        }
    }
}
